package com.starrin.tennisfinder.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * User: Starrin
 * Date: 2013-10-17
 * Time: 00:10
 */
public class WebUtil {
    /**
     * Returns the output from the given URL.
     * <p/>
     * I tried to hide some of the ugliness of the exception-handling
     * in this method, and just return a high level Exception from here.
     * Modify this behavior as desired.
     *
     * @param desiredUrl
     * @return
     * @throws Exception
     */
    static public String doHttpUrlConnectionAction(String desiredUrl)
            throws Exception {
        URL url;
        BufferedReader reader = null;
        StringBuilder stringBuilder;

        try {
            // create the HttpURLConnection
            url = new URL(desiredUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // just want to do an HTTP GET here
            connection.setRequestMethod("GET");

            // uncomment this if you want to write output to this url
            //connection.setDoOutput(true);

            // give it 15 seconds to respond
            connection.setReadTimeout(15 * 1000);
            connection.connect();

            // read the output from the server
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            // close the reader; this can throw an exception too, so
            // wrap it in another try/catch block.
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

    public static String getReducedResponse(String response, String startSearchPoint) {
        if(!response.contains(startSearchPoint)) {
            return null;
        }
        response = response.substring(response.indexOf(startSearchPoint));
        return response;
    }

    public static String getReducedResponse(String response, String startSearchPoint, String stopSearchPoint) {
        if(!response.contains(startSearchPoint) || !response.contains(stopSearchPoint)) {
            return null;
        }
        response = response.substring(response.indexOf(startSearchPoint), response.indexOf(stopSearchPoint));
        return response;
    }
}



